package com.cyzy.listener;

import com.alibaba.fastjson.JSON;
import com.cyzy.pojo.Orders;
import com.cyzy.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.listener.KeyExpirationEventMessageListener;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.stereotype.Component;

@Component
public class RedisKeyExpirationListener extends KeyExpirationEventMessageListener {

    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    @Autowired
    private OrderService orderService;

    // Key命名规则常量
    private static final String TIMER_KEY_PREFIX = "product:order:timer:data:";
    private static final String DATA_KEY_PREFIX = "product:order:data:";

    public RedisKeyExpirationListener(RedisMessageListenerContainer listenerContainer) {
        super(listenerContainer);
    }

    /**
     * 核心逻辑：处理键过期事件
     * @param message 过期Key的消息对象
     * @param pattern 通道模式
     */
    @Override
    public void onMessage(Message message, byte[] pattern) {
        // 1. 获取过期的定时Key
        String expiredTimerKey = message.toString();

        // 2. 验证是否为关注的定时Key
        if (expiredTimerKey.startsWith(TIMER_KEY_PREFIX)) {
            // 3. 从定时Key提取数据ID (示例格式: timer:data:ORDER_12345)
            String dataId = expiredTimerKey.substring(TIMER_KEY_PREFIX.length());

            // 4. 构造真实数据Key
            String dataKey = DATA_KEY_PREFIX + dataId;

            // 5. 从Redis获取存储的数据
             String businessData = redisTemplate.opsForValue().get(dataKey);

            if (businessData != null) {
                // 6. 执行业务逻辑 (示例：订单超时处理)
                handleBusinessLogic(dataId, businessData);

                // 7. 清理数据Key
                redisTemplate.delete(dataKey);
            }
        }
    }

    /**
     * 实际业务处理逻辑
     * @param dataId 数据标识符
     * @param businessData 业务数据对象
     */
    private void handleBusinessLogic(String dataId, String businessData) {
        // 这里实现您的具体业务逻辑
        // 示例：订单超时处理、缓存清理等
//        Orders orders = JSON.parseObject(businessData, Orders.class);
//        orders.setOrderStatus(0);
//        orderService.updateOrder(orders);
//        System.out.println("处理数据过期回调, ID: " + dataId);
//        System.out.println("业务数据: " + businessData);
    }
}